# -*- coding: utf-8 -*-
from django.shortcuts import render
from django.shortcuts import render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from django.forms import ModelForm
from accounts.models import *
from accounts.forms import * 

from django.contrib.auth import authenticate
from django.views.decorators.csrf import csrf_exempt
from django import forms
from django.core.exceptions import ValidationError

import re
import json
import time
from chitchatSettings import ChitchatDatabase
from chitchatLogging import ChitchatLogger
import chitchatMongo

# Initiate MongoDB connection and logger
ccDb = ChitchatDatabase()
mongoConn = ccDb.ccMongo()
chatLogger = ChitchatLogger("chatLog")

def polling(request):
    # TODO: Get the two params from request.
    # uid = 
    # poll_start =      
    count = 0
    fetch_time = poll_start
    result = []
    while (fetch_time - poll_start < 60.0):
        ret = chitchatMongo.fetch_new(uid, fetch_time)
        count += 1
        if (ret.count() != 0 and ret != -1):
            for item in ret:
                result.append(item["message"])
            try:
                rem = mongoConn.chitchat.newmsg.remove({"to" : uid,
                                                "timestamp" : {"$lt" : fetch_time}})
                if rem.get("n") != len(result):
                    chatLogger.log.warning("Polling removed " + str(rem.get("n")) + 
                                    " from Mongo but returned " + str(len(result)))
            except Exception as _Eall:
                chatLogger.log.error(_Eall)
                return -1
            break
        else:
            time.sleep(1)
            fetch_time = time.time()
    print(count)
    # TODO: Render here.
    return result

def send_message(request):
    """
    --
    @request        Containing:
                    session - UserID, ChatID
                    message
    """
    # TODO: Get the five params from request.
    # uid1 =   # From which user
    # uid2 =   # To which user
    # timestamp =
    # msg = 
    # date = 
    chitchatMongo.add_message(uid1, uid2, msg, date, timestamp)
    # Detect link and produce preview
    # Render should be handled by front-end
    return 0

